package yxy.game.pm2.command.arena;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ArenaMessage;
import yxy.game.pm2.module.arena.ArenaHandle;
import yxy.game.pm2.module.arena.ArenaPlayerModule;

/** 竞技场 刷新对手 */
@MessageType(proto = Command.ArenaRivalUpdate, classtype = ArenaMessage.ArenaRivalUpdateRequest.class)
public class CMD_ArenaRivalUpdate extends Command<ArenaMessage.ArenaRivalUpdateRequest> {

	@Override
	public void execute(MessageSource messageSource, ArenaMessage.ArenaRivalUpdateRequest request) {
		String playerCode = messageSource.getTag();

		ArenaMessage.ArenaRivalUpdateResponse.Builder response = ArenaMessage.ArenaRivalUpdateResponse.newBuilder();

		ArenaPlayerModule module = ArenaPlayerModule.get(playerCode);
		if (module == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 竞技场模块没有开启
			return;
		}
		try {
			if (module.tryLock()) {
				response.addAllOppo(new ArenaHandle().refreshOppo(module));

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			module.unlock();
		}
	}

	private void send(MessageSource messageSource, ArenaMessage.ArenaRivalUpdateResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}